/** 
 *  ESP32 (M5stackCore2)
 *  Arduino
 *  lvgl8
 *  by Forairaaaaa
 **/

#include "../.pio/libdeps/m5stack-core2/M5Core2/src/M5Core2.h"
#include "../.pio/libdeps/m5stack-core2/lvgl/lvgl.h"
#include "../.pio/libdeps/m5stack-core2/lv_examples/lv_demo.h"
#include "../lib/my_lvgl_apps/my_lvgl_apps.h"



// define
/* LVGL setup */
#define screenWidth   320
#define screenHeight  240
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf1[ screenWidth * 24 ];
static lv_color_t buf2[ screenWidth * 24 ];
void LVGL_begin(void);
/* ----------- */
// your code:




void setup()
{
    LVGL_begin();

    // lv_demo_benchmark();
    // lv_demo_widgets();
    // lv_demo_music();

    // app_2();
    app_setting_LCD_Bri();


    Serial.println("LVGL loaded..");

    // xTaskCreatePinnedToCore(blink, "blinkTask", 4096, NULL, 0, NULL, 1);
}








/* loop for lvgl handler */
void loop()
{
    lv_timer_handler();  /* let the GUI do its work */
    delay(5);
}
/* Display flushing */
void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p )
{
    uint32_t w = ( area->x2 - area->x1 + 1 );
    uint32_t h = ( area->y2 - area->y1 + 1 );

    M5.Lcd.startWrite();
    M5.Lcd.setAddrWindow( area->x1, area->y1, w, h );
    M5.Lcd.pushColors( &color_p->full, w * h, true );
    M5.Lcd.endWrite();

    lv_disp_flush_ready( disp );
}
/* Read the touchpad */
void my_touchpad_read( lv_indev_drv_t * indev_driver, lv_indev_data_t * data )
{
    TouchPoint_t pos = M5.Touch.getPressPoint();
    bool touched = ( pos.x == -1 ) ? false : true;
    if(!touched) {
        data->state = LV_INDEV_STATE_REL;
    } else {
        data->state = LV_INDEV_STATE_PR; 
        data->point.x = pos.x;
        data->point.y = pos.y;
        // Serial.print(pos.x);Serial.print(" : ");Serial.println(pos.y);
    }
}
/* lvgl serial log */
// void my_log_cb(const char * buf)
// {
//   Serial.println(buf);
// }
/* lvgl begin */
void LVGL_begin(void)
{
    // lvgl init
    lv_init();
    // m5core2 init
    M5.begin();
    // reset power led
    M5.Axp.SetLed(0);

    // draw buff init
    lv_disp_draw_buf_init( &draw_buf, buf1, buf2, screenWidth * 24 );

    /*Initialize the display*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init( &disp_drv );
    /*Change the following line to your display resolution*/
    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;

    disp_drv.draw_buf = &draw_buf;
    disp_drv.flush_cb = my_disp_flush;
    // disp_drv.full_refresh = 1;
    lv_disp_drv_register( &disp_drv );

    /*Initialize the (dummy) input device driver*/
    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init( &indev_drv );
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = my_touchpad_read;
    lv_indev_drv_register( &indev_drv );

    /* lvgl log */
    // lv_log_register_print_cb(my_log_cb);
}
